#include "snake.h"
#include <iostream>

Snake::Snake(int screenWidth, int screenHeight, int gridSize)
    : screenWidth(screenWidth), screenHeight(screenHeight), gridSize(gridSize) {
    // 初始化蛇身
    int startX = screenWidth / 2;
    int startY = screenHeight / 2;
    body.emplace_back(startX, startY, gridSize, gridSize);
    direction = 1; // 初始方向向右

    // 添加初始蛇身（3节）
    for (int i = 1; i < 4; i++) {
        body.emplace_back(startX - i * gridSize, startY, gridSize, gridSize);
    }
}

void Snake::move() {
    if (body.empty()) return;

    // 保存尾部位置用于增长
    RectangleCollisionBox tail = body.back();

    // 移动身体（从尾部向前移动）
    for (size_t i = body.size() - 1; i > 0; --i) {
        body[i] = body[i - 1];
    }

    // 移动头部
    RectangleCollisionBox& head = body[0];
    float newX = head.getX();
    float newY = head.getY();

    switch (direction) {
    case 0: newY -= gridSize; break; // 上
    case 1: newX += gridSize; break; // 右
    case 2: newY += gridSize; break; // 下
    case 3: newX -= gridSize; break; // 左
    }

    head.setX(newX);
    head.setY(newY);
}

void Snake::changeDirection(int newDirection) {
    // 防止180度转向
    if ((direction == 0 && newDirection == 2) ||
        (direction == 2 && newDirection == 0) ||
        (direction == 1 && newDirection == 3) ||
        (direction == 3 && newDirection == 1)) {
        return;
    }
    direction = newDirection;
}

bool Snake::checkCollision(const CollisionBox& other) const {
    if (body.empty()) return false;
    return body[0].checkCollision(other);
}

void Snake::grow() {
    if (body.empty()) return;
    body.push_back(body.back());
}

const std::vector<RectangleCollisionBox>& Snake::getBody() const {
    return body;
}

const RectangleCollisionBox& Snake::getHead() const {
    return body[0];
}

int Snake::getDirection() const {
    return direction;
}